<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧控制面板 -->
      <el-col :span="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>地图控制</span>
          </div>
          
          <!-- 地址搜索 -->
          <el-form :model="searchForm" :inline="true" class="search-form">
            <el-form-item label="搜索模式">
              <el-radio-group v-model="searchForm.mode">
                <el-radio label="around">周边搜索</el-radio>
                <el-radio label="nationwide">全国搜索</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="关键词" v-if="searchForm.mode === 'around'">
              <el-input
                v-model="searchForm.keywords"
                placeholder="请输入搜索关键词"
                style="width: 200px"
              />
            </el-form-item>
            
            <el-form-item label="关键词" v-if="searchForm.mode === 'nationwide'">
              <el-input
                v-model="searchForm.keywords"
                placeholder="请输入搜索关键词"
                style="width: 200px"
              />
            </el-form-item>
            
            <el-form-item label="城市" v-if="searchForm.mode === 'nationwide'">
              <el-input
                v-model="searchForm.city"
                placeholder="请输入城市名称（可选）"
                style="width: 200px"
              />
            </el-form-item>
            
            <el-form-item label="半径" v-if="searchForm.mode === 'around'">
              <el-select v-model="searchForm.radius" style="width: 120px">
                <el-option label="1公里" :value="1000" />
                <el-option label="3公里" :value="3000" />
                <el-option label="5公里" :value="5000" />
                <el-option label="10公里" :value="10000" />
              </el-select>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="handleSearchPoi" :loading="loading">
                搜索
              </el-button>
              <el-button @click="clearMap">清空</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 搜索结果 -->
          <el-card class="search-results" v-if="searchResults.length > 0">
            <div slot="header">
              <span>搜索结果 ({{ searchResults.length }})</span>
            </div>
            <el-table :data="searchResults" style="width: 100%">
              <el-table-column prop="name" label="名称" width="200" />
              <el-table-column prop="address" label="地址" />
              <el-table-column prop="city" label="城市" width="100" />
              <el-table-column prop="distance" label="距离" width="100" v-if="searchForm.mode === 'around'">
                <template slot-scope="scope">
                  {{ scope.row.distance ? (scope.row.distance / 1000).toFixed(1) + 'km' : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template slot-scope="scope">
                  <el-button size="mini" @click="locateOnMap(scope.row)">定位</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-card>
      </el-col>
      
      <!-- 右侧地图区域 -->
      <el-col :span="18">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>高德地图</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="refreshMap">
              刷新地图
            </el-button>
          </div>
          
          <!-- 地图容器 -->
          <div id="map-container" style="height: 600px; width: 100%;"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getMapConfig, geocode, searchPoi, searchPoiNationwide } from '@/api/map'

export default {
  name: 'MapIndex',
  data() {
    return {
      map: null,
      searchForm: {
        address: '',
        keywords: '',
        radius: 1000,
        mode: 'around', // 新增搜索模式
        city: '' // 新增城市
      },
      searchResults: [],
      loading: false,
      mapConfig: null
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    // 初始化地图
    async initMap() {
      try {
        console.log('开始初始化地图...')
        // 获取地图配置
        const response = await getMapConfig()
        console.log('地图配置响应:', response)
        if (response.code === 200) {
          this.mapConfig = response.data
          this.loadAmapScript()
        } else {
          this.$message.error(`获取地图配置失败: ${response.msg}`)
        }
      } catch (error) {
        console.error('地图初始化错误:', error)
        this.$message.error(`获取地图配置失败: ${error.message}`)
      }
    },
    
    // 加载高德地图脚本
    loadAmapScript() {
      // 检查是否已加载
      if (window.AMap) {
        this.createMap()
        return
      }
      
      const script = document.createElement('script')
      script.src = `https://webapi.amap.com/maps?v=${this.mapConfig.version}&key=${this.mapConfig.key}&plugin=${this.mapConfig.plugin}`
      script.onload = () => {
        this.createMap()
      }
      script.onerror = () => {
        this.$message.error('高德地图脚本加载失败')
      }
      document.head.appendChild(script)
    },
    
    // 创建地图
    createMap() {
      try {
        this.map = new AMap.Map('map-container', {
          zoom: 11,
          center: [116.397428, 39.90923], // 北京天安门
          mapStyle: 'amap://styles/normal'
        })
        
        // 添加地图控件
        this.map.addControl(new AMap.Scale())
        this.map.addControl(new AMap.ToolBar())
        
        // 添加点击事件
        this.map.on('click', (e) => {
          this.handleMapClick(e)
        })
        
        this.$message.success('地图初始化成功')
      } catch (error) {
        this.$message.error('地图创建失败')
        console.error(error)
      }
    },
    
    // 地理编码
    async handleGeocode() {
      if (!this.searchForm.address) {
        this.$message.warning('请输入地址')
        return
      }
      
      try {
        this.loading = true
        const response = await geocode(this.searchForm.address)
        if (response.code === 200 && response.data.status === '1') {
          const geocodes = response.data.geocodes
          if (geocodes && geocodes.length > 0) {
            const location = geocodes[0].location.split(',')
            const lng = parseFloat(location[0])
            const lat = parseFloat(location[1])
            
            // 添加标记
            this.addMarker([lng, lat], this.searchForm.address)
            
            // 移动到该位置
            this.map.setCenter([lng, lat])
            this.map.setZoom(15)
            
            this.$message.success('地址定位成功')
          }
        } else {
          this.$message.error(response.data.info || '地理编码失败')
        }
      } catch (error) {
        this.$message.error('地理编码请求失败')
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    
    // 搜索POI
    async handleSearchPoi() {
      if (!this.searchForm.keywords) {
        this.$message.warning('请输入搜索关键词')
        return
      }
      
      try {
        this.loading = true
        console.log('开始搜索，模式:', this.searchForm.mode)
        console.log('搜索参数:', this.searchForm)
        
        let response
        
        if (this.searchForm.mode === 'nationwide') {
          // 全国范围搜索
          console.log('执行全国范围搜索...')
          response = await searchPoiNationwide(
            this.searchForm.keywords,
            this.searchForm.city
          )
        } else {
          // 周边搜索
          console.log('执行周边搜索...')
          const center = this.map.getCenter()
          const location = `${center.lng},${center.lat}`
          console.log('地图中心位置:', location)
          
          response = await searchPoi(
            this.searchForm.keywords,
            location,
            this.searchForm.radius
          )
        }
        
        console.log('搜索响应:', response)
        
        if (response.code === 200 && response.data.status === '1') {
          const pois = response.data.pois || []
          console.log('找到POI数量:', pois.length)
          console.log('POI数据:', pois)
          
          this.searchResults = pois.map(poi => ({
            name: poi.name,
            address: poi.address,
            distance: poi.distance,
            location: poi.location,
            city: poi.cityname || poi.adname || ''
          }))
          
          // 在地图上显示搜索结果
          this.displaySearchResults(pois)
          
          this.$message.success(`找到 ${pois.length} 个结果`)
        } else {
          console.error('搜索失败:', response.data)
          this.$message.error(response.data.info || '搜索失败')
        }
      } catch (error) {
        console.error('搜索请求失败:', error)
        this.$message.error('搜索请求失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    
    // 在地图上显示搜索结果
    displaySearchResults(pois) {
      // 清除之前的标记
      this.clearMarkers()
      
      if (pois && pois.length > 0) {
        // 计算所有POI的中心点
        let totalLng = 0
        let totalLat = 0
        let validCount = 0
        
        pois.forEach(poi => {
          if (poi.location) {
            const location = poi.location.split(',')
            const lng = parseFloat(location[0])
            const lat = parseFloat(location[1])
            
            if (!isNaN(lng) && !isNaN(lat)) {
              totalLng += lng
              totalLat += lat
              validCount++
              
              // 添加标记
              this.addMarker([lng, lat], poi.name, 'search')
            }
          }
        })
        
        // 如果找到了有效位置，将地图中心移动到搜索结果区域
        if (validCount > 0) {
          const centerLng = totalLng / validCount
          const centerLat = totalLat / validCount
          
          // 移动地图到搜索结果区域
          this.map.setCenter([centerLng, centerLat])
          
          // 根据搜索结果数量调整缩放级别
          if (validCount === 1) {
            this.map.setZoom(16) // 单个结果，放大显示
          } else if (validCount <= 5) {
            this.map.setZoom(14) // 少量结果，中等缩放
          } else {
            this.map.setZoom(12) // 多个结果，缩小显示
          }
          
          this.$message.success(`地图已定位到搜索结果区域`)
        }
      }
    },
    
    // 添加标记
    addMarker(position, title, type = 'normal') {
      const marker = new AMap.Marker({
        position: position,
        title: title,
        icon: type === 'search' ? 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png' : undefined
      })
      
      marker.setMap(this.map)
      
      // 添加信息窗体
      const infoWindow = new AMap.InfoWindow({
        content: `<div style="padding: 10px;">
          <h4>${title}</h4>
          <p>经度: ${position[0]}</p>
          <p>纬度: ${position[1]}</p>
        </div>`
      })
      
      marker.on('click', () => {
        infoWindow.open(this.map, position)
      })
    },
    
    // 清除标记
    clearMarkers() {
      // 这里可以通过维护一个标记数组来清除，简化起见暂时重新创建地图
      this.map.clearMap()
      this.createMap()
    },
    
    // 清空地图
    clearMap() {
      this.searchResults = []
      this.searchForm.address = ''
      this.searchForm.keywords = ''
      this.searchForm.city = '' // 清空城市
      this.searchForm.mode = 'around' // 重置搜索模式
      this.clearMarkers()
    },
    
    // 刷新地图
    refreshMap() {
      this.clearMap()
      this.initMap()
    },
    
    // 地图点击事件
    handleMapClick(e) {
      const lng = e.lnglat.getLng()
      const lat = e.lnglat.getLat()
      
      this.$message.info(`点击位置: 经度 ${lng.toFixed(6)}, 纬度 ${lat.toFixed(6)}`)
    },
    
    // 搜索结果点击
    handleResultClick(item) {
      const location = item.location.split(',')
      const lng = parseFloat(location[0])
      const lat = parseFloat(location[1])
      
      this.map.setCenter([lng, lat])
      this.map.setZoom(16)
      
      // 高亮显示选中的标记
      this.clearMarkers()
      this.addMarker([lng, lat], item.name, 'selected')
    },

    // 定位到地图
    locateOnMap(item) {
      const location = item.location.split(',')
      const lng = parseFloat(location[0])
      const lat = parseFloat(location[1])
      
      this.map.setCenter([lng, lat])
      this.map.setZoom(16)
      
      // 高亮显示选中的标记
      this.clearMarkers()
      this.addMarker([lng, lat], item.name, 'selected')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-results {
  margin-top: 20px;
}

.map-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

#map-container {
  height: 600px;
  width: 100%;
}

.search-result-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-result-item:hover {
  background-color: #f5f7fa;
}

.result-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.result-address {
  color: #606266;
  font-size: 14px;
  margin-bottom: 3px;
}

.result-distance {
  color: #909399;
  font-size: 12px;
}

.box-card {
  margin-bottom: 20px;
}
</style>
